﻿using UnityEditor;
using UnityEngine;

namespace CWM.Skinn
{
    public static partial class SkinnContext
    {
        public static class MenuBones
        {
            public static string MethodID = "";

            public static bool ContextShown = true;

            public static void ContextGUI(int id, Rect selectionRect)
            {
                if (ContextShown || InstanceIDs.Count < 1) return;
                ContextShown = true;
                ShowContextMenu();
            }

            public static void ShowContextMenu()
            {
                ContextBone1 = -1;
                var allBones = ContextUtility.GetAllBones();

                GenericMenu menu = new GenericMenu();
                var boneContext0 = SkinnEx.FindGameObject(SkinnContext.ContextBone0);
                var label = boneContext0 ? boneContext0.name + " + " : "";
                menu.AddDisabledItem(new GUIContent(label));
                menu.AddSeparator("");
                menu.AddItem(new GUIContent("Cancel"), false, ContextMenuSelected, "Cancel");
                menu.AddSeparator("");

                foreach (var bone in allBones)
                {
                    var id = bone.Value.bone;
                    var subLabel = bone.Value.name;

                    if (id.gameObject.GetInstanceID() == ContextBone0) menu.AddDisabledItem(new GUIContent(subLabel));
                    else menu.AddItem(new GUIContent(subLabel), false, ContextMenuSelected, id);
                }

                menu.ShowAsContext();
            }

            private static void ContextMenuSelected(object id)
            {
                var bone = id as Transform; if (!bone) return;
                ContextBone1 = bone.gameObject.GetInstanceID();
                InvokeContext(MethodID);
            }
        }
    }
}
